package com.micro.ai.files.controller;

import com.micro.ai.commons.domain.ApiResponse;
import com.micro.ai.files.entity.StorageQuota;
import com.micro.ai.files.service.StorageQuotaService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

/**
 * 存储配额控制器
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/storage-quotas")
@Tag(name = "存储配额管理", description = "存储配额的查询、更新等功能")
public class StorageQuotaController {

    @Autowired
    private StorageQuotaService storageQuotaService;

    @GetMapping("/{tenantId}")
    @PreAuthorize("hasAuthority('storage_quota:view')")
    @Operation(summary = "获取或创建配额", description = "获取租户的存储配额，如果不存在则创建")
    public ApiResponse<StorageQuota> getOrCreate(
            @Parameter(description = "租户ID", required = true) @PathVariable String tenantId) {
        StorageQuota quota = storageQuotaService.getOrCreate(tenantId);
        return ApiResponse.success(quota);
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('storage_quota:update')")
    @Operation(summary = "更新配额", description = "更新存储配额信息")
    public ApiResponse<StorageQuota> update(
            @Parameter(description = "配额ID", required = true) @PathVariable String id,
            @Valid @RequestBody StorageQuota quota) {
        StorageQuota result = storageQuotaService.update(id, quota);
        return ApiResponse.success("更新成功", result);
    }

    @GetMapping("/{tenantId}/check")
    @PreAuthorize("hasAuthority('storage_quota:view')")
    @Operation(summary = "检查配额", description = "检查配额是否足够")
    public ApiResponse<Boolean> checkQuota(
            @Parameter(description = "租户ID", required = true) @PathVariable String tenantId,
            @Parameter(description = "文件大小（字节）", required = true) @RequestParam("fileSize") Long fileSize) {
        boolean enough = storageQuotaService.checkQuota(tenantId, fileSize);
        return ApiResponse.success(enough);
    }

    @GetMapping("/{tenantId}/usage-rate")
    @PreAuthorize("hasAuthority('storage_quota:view')")
    @Operation(summary = "获取使用率", description = "获取存储使用率（百分比）")
    public ApiResponse<Double> getUsageRate(
            @Parameter(description = "租户ID", required = true) @PathVariable String tenantId) {
        double rate = storageQuotaService.getUsageRate(tenantId);
        return ApiResponse.success(rate);
    }
}

